package com.arvin.faceDetect.ui

import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.util.Log
import android.view.Menu
import android.view.MenuItem
import android.widget.ImageView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.content.FileProvider
import androidx.core.view.isVisible
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.GridLayoutManager
import com.arvin.faceDetect.R
import com.arvin.faceDetect.adapter.FaceListAdapter
import com.arvin.faceDetect.databinding.ActivityFaceManagementBinding
import com.arvin.faceDetect.db.FaceDatabase
import com.arvin.faceDetect.db.FaceEntity
import com.arvin.faceDetect.utils.LogUtils
import com.google.android.material.dialog.MaterialAlertDialogBuilder
import com.google.android.material.textfield.TextInputEditText
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.io.File
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import java.util.zip.ZipEntry
import java.util.zip.ZipOutputStream

class FaceManagementActivity : AppCompatActivity() {
    private lateinit var binding: ActivityFaceManagementBinding
    private lateinit var faceListAdapter: FaceListAdapter
    private var isSelectionMode = false
    private var actionMode: androidx.appcompat.view.ActionMode? = null

    private val actionModeCallback = object : androidx.appcompat.view.ActionMode.Callback {
        override fun onCreateActionMode(
            mode: androidx.appcompat.view.ActionMode,
            menu: Menu
        ): Boolean {
            mode.menuInflater.inflate(R.menu.menu_face_selection, menu)
            return true
        }

        override fun onPrepareActionMode(
            mode: androidx.appcompat.view.ActionMode,
            menu: Menu
        ): Boolean {
            return false
        }

        override fun onActionItemClicked(
            mode: androidx.appcompat.view.ActionMode,
            item: MenuItem
        ): Boolean {
            return when (item.itemId) {
                R.id.action_select_all -> {
                    faceListAdapter.selectAll()
                    updateSelectionUI()
                    true
                }

                R.id.action_delete -> {
                    showDeleteConfirmDialog()
                    true
                }

                else -> false
            }
        }

        override fun onDestroyActionMode(mode: androidx.appcompat.view.ActionMode) {
            exitSelectionMode()
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        binding = ActivityFaceManagementBinding.inflate(layoutInflater)
        setContentView(binding.root)

        setupToolbar()
        setupRecyclerView()
        setupFabAddFace()
        observeFaces()
    }

    private fun setupToolbar() {
        setSupportActionBar(binding.toolbar)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)
    }

    override fun onCreateOptionsMenu(menu: Menu): Boolean {
        menuInflater.inflate(R.menu.menu_face_management, menu)
        return true
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        return when (item.itemId) {
            android.R.id.home -> {
                onBackPressed()
                true
            }

            R.id.action_search -> {
                val searchView = item.actionView as androidx.appcompat.widget.SearchView
                setupSearchView(searchView)
                true
            }

            R.id.action_export -> {
                exportFaceData()
                true
            }

            else -> super.onOptionsItemSelected(item)
        }
    }

    private fun setupSearchView(searchView: androidx.appcompat.widget.SearchView) {
        searchView.setOnQueryTextListener(object :
            androidx.appcompat.widget.SearchView.OnQueryTextListener {
            override fun onQueryTextSubmit(query: String?): Boolean {
                return false
            }

            override fun onQueryTextChange(newText: String?): Boolean {
                searchFaces(newText.orEmpty())
                return true
            }
        })
    }

    private fun setupRecyclerView() {
        Log.d("FaceManagement", "开始设置RecyclerView")
        faceListAdapter = FaceListAdapter(
            onItemClick = { face: FaceEntity ->
                Log.d("FaceManagement", "点击人脸项 - ID: ${face.id}, 姓名: ${face.name}")
                if (isSelectionMode) {
                    faceListAdapter.toggleSelection(face)
                    updateSelectionUI()
                } else {
                    showEditFaceDialog(face)
                }
            },
            onItemLongClick = { face: FaceEntity ->
                Log.d("FaceManagement", "长按人脸项 - ID: ${face.id}, 姓名: ${face.name}")
                if (!isSelectionMode) {
                    enterSelectionMode()
                    faceListAdapter.toggleSelection(face)
                    updateSelectionUI()
                }
                true
            }
        )

        binding.rvFaces.apply {
            layoutManager = GridLayoutManager(this@FaceManagementActivity, 3)
            adapter = faceListAdapter
            Log.d(
                "FaceManagement", """
                RecyclerView初始化完成:
                - 布局管理器: $layoutManager
                - 适配器: $adapter
                - 是否可见: $isVisible
            """.trimIndent()
            )
        }
    }

    private fun setupFabAddFace() {
        binding.fabAddFace.setOnClickListener {
            startActivity(Intent(this, FaceAutoCollectActivity::class.java))
        }
    }

    private fun observeFaces() {
        Log.d("FaceManagement", "开始观察人脸数据")
        lifecycleScope.launch {
            try {
                Log.d("FaceManagement", "开始从数据库获取人脸数据")
                FaceDatabase.getDatabase(this@FaceManagementActivity)
                    .faceDao()
                    .getAllFaces()
                    .collect { faces ->
                        Log.d("FaceManagement", "收到人脸数据更新 - 数量: ${faces.size}")
                        faces.forEach { face ->
                            Log.d(
                                "FaceManagement",
                                "人脸数据 - ID: ${face.id}, 姓名: ${face.name}, 创建时间: ${
                                    formatTime(face.createTime)
                                }"
                            )
                        }
                        faceListAdapter.submitList(faces)
                        updateEmptyView(faces.isEmpty())

                        // 检查RecyclerView状态
                        binding.rvFaces.post {
                            Log.d(
                                "FaceManagement", """
                                RecyclerView状态:
                                - 是否可见: ${binding.rvFaces.isVisible}
                                - 项目数量: ${faceListAdapter.itemCount}
                                - 布局管理器: ${binding.rvFaces.layoutManager}
                                - 尺寸: ${binding.rvFaces.width}x${binding.rvFaces.height}
                            """.trimIndent()
                            )
                        }
                    }
            } catch (e: Exception) {
                Log.e("FaceManagement", "获取人脸数据失败", e)
            }
        }
    }

    private fun updateEmptyView(isEmpty: Boolean) {
        Log.d("FaceManagement", "更新空视图状态: isEmpty=$isEmpty")
        binding.rvFaces.isVisible = !isEmpty
        binding.tvEmpty.isVisible = isEmpty
    }

    private fun enterSelectionMode() {
        isSelectionMode = true
        actionMode = startSupportActionMode(actionModeCallback)
    }

    private fun exitSelectionMode() {
        isSelectionMode = false
        actionMode = null
        faceListAdapter.clearSelection()
    }

    private fun updateSelectionUI() {
        val selectedCount = faceListAdapter.getSelectedItems().size
        actionMode?.title = "已选择 $selectedCount 项"
    }

    private fun showDeleteConfirmDialog() {
        val selectedItems = faceListAdapter.getSelectedItems()
        if (selectedItems.isEmpty()) return

        MaterialAlertDialogBuilder(this)
            .setTitle("删除确认")
            .setMessage("确定要删除选中的 ${selectedItems.size} 个人脸吗？")
            .setPositiveButton("删除") { _, _ ->
                lifecycleScope.launch {
                    withContext(Dispatchers.IO) {
                        FaceDatabase.getDatabase(this@FaceManagementActivity)
                            .faceDao()
                            .deleteFaces(selectedItems)
                    }
                    exitSelectionMode()
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun showEditFaceDialog(face: FaceEntity) {
        val dialogView = layoutInflater.inflate(R.layout.dialog_edit_face, null)
        val imageView = dialogView.findViewById<ImageView>(R.id.ivFace)

        // 设置ImageView的高度为宽度的1.25倍（4:5比例）
        imageView.post {
            val width = imageView.width
            val height = (width * 1.25f).toInt()
            val params = imageView.layoutParams
            params.height = height
            imageView.layoutParams = params

            // 设置图片
            imageView.setImageBitmap(face.faceImage)
        }
        
        val etName = dialogView.findViewById<TextInputEditText>(R.id.etName)
        etName.setText(face.name)

        MaterialAlertDialogBuilder(this)
            .setTitle("编辑人脸")
            .setView(dialogView)
            .setPositiveButton("保存") { _, _ ->
                val newName = etName.text.toString()
                if (newName.isNotBlank()) {
                    updateFaceName(face, newName)
                }
            }
            .setNegativeButton("取消", null)
            .show()
    }

    private fun updateFaceName(face: FaceEntity, newName: String) {
        lifecycleScope.launch {
            try {
                val updatedFace = face.copy(name = newName)
                withContext(Dispatchers.IO) {
                    FaceDatabase.getDatabase(this@FaceManagementActivity)
                        .faceDao()
                        .updateFace(updatedFace)
                }
                Toast.makeText(this@FaceManagementActivity, "更新成功", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                Toast.makeText(
                    this@FaceManagementActivity,
                    "更新失败: ${e.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun searchFaces(query: String) {
        lifecycleScope.launch {
            try {
                val faces = withContext(Dispatchers.IO) {
                    if (query.isBlank()) {
                        FaceDatabase.getDatabase(this@FaceManagementActivity).faceDao()
                            .getAllFacesList()
                    } else {
                        FaceDatabase.getDatabase(this@FaceManagementActivity).faceDao()
                            .searchFaces("%$query%")
                    }
                }
                faceListAdapter.submitList(faces)
                updateEmptyView(faces.isEmpty())
            } catch (e: Exception) {
                Toast.makeText(
                    this@FaceManagementActivity,
                    "搜索失败: ${e.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun exportFaceData() {
        lifecycleScope.launch {
            try {
                // 获取所有人脸数据
                val faces = withContext(Dispatchers.IO) {
                    FaceDatabase.getDatabase(this@FaceManagementActivity)
                        .faceDao()
                        .getAllFacesList()
                }

                if (faces.isEmpty()) {
                    Toast.makeText(
                        this@FaceManagementActivity,
                        "没有可导出的人脸数据",
                        Toast.LENGTH_SHORT
                    ).show()
                    return@launch
                }

                // 创建导出目录
                val exportDir = File(getExternalFilesDir(null), "face_export")
                if (!exportDir.exists()) {
                    exportDir.mkdirs()
                }

                // 创建导出文件
                val timestamp =
                    SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(Date())
                val exportFile = File(exportDir, "face_data_${timestamp}")
                if (!exportFile.exists()) {
                    exportFile.mkdirs()
                }

                // 导出数据
                withContext(Dispatchers.IO) {
                    // 导出人脸信息到CSV文件
                    val csvFile = File(exportFile, "face_info.csv")
                    csvFile.bufferedWriter().use { writer ->
                        writer.write("ID,姓名,创建时间\n")
                        faces.forEach { face ->
                            writer.write("${face.id},${face.name},${formatTime(face.createTime)}\n")
                        }
                    }

                    // 导出人脸图片
                    faces.forEach { face ->
                        val imageFile = File(exportFile, "face_${face.id}.jpg")
                        imageFile.outputStream().use { output ->
                            face.faceImage?.compress(Bitmap.CompressFormat.JPEG, 100, output)
                        }
                    }
                }

                // 创建ZIP文件
                val zipFile = File(exportDir, "face_data_${timestamp}.zip")
                withContext(Dispatchers.IO) {
                    ZipOutputStream(zipFile.outputStream()).use { zip ->
                        exportFile.walkTopDown().forEach { file ->
                            if (file.isFile) {
                                val entry = ZipEntry(file.relativeTo(exportFile).path)
                                zip.putNextEntry(entry)
                                file.inputStream().use { input ->
                                    input.copyTo(zip)
                                }
                                zip.closeEntry()
                            }
                        }
                    }
                }

                // 删除临时目录
                exportFile.deleteRecursively()

                // 分享ZIP文件
                val uri = FileProvider.getUriForFile(
                    this@FaceManagementActivity,
                    "${packageName}.provider",
                    zipFile
                )

                val intent = Intent(Intent.ACTION_SEND).apply {
                    type = "application/zip"
                    putExtra(Intent.EXTRA_STREAM, uri)
                    addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                }

                startActivity(Intent.createChooser(intent, "分享导出文件"))

                // 记录日志
                LogUtils.i("FaceManagement", "导出${faces.size}个人脸数据到${zipFile.name}")

                Toast.makeText(this@FaceManagementActivity, "导出成功", Toast.LENGTH_SHORT).show()
            } catch (e: Exception) {
                LogUtils.e("FaceManagement", "导出人脸数据失败", e)
                Toast.makeText(
                    this@FaceManagementActivity,
                    "导出失败：${e.message}",
                    Toast.LENGTH_SHORT
                ).show()
            }
        }
    }

    private fun formatTime(timestamp: Long): String {
        val sdf = SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.getDefault())
        return sdf.format(Date(timestamp))
    }
} 